package com.example.springbootredisdemo.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * jackson 工具类    依赖 spring-boot-starter-web   依赖传递  注意版本目前的工具类在由springboot 2.3.4.RELEASE 依赖引入
 *
 * @author yan.liang@ustcinfo.com
 * @date 2017/6/10
 */
public class JSONUtils {
    private final static ObjectMapper objectMapper = new ObjectMapper()
            .registerModule(new ParameterNamesModule())
            .registerModule(new Jdk8Module())
            .registerModule(new JavaTimeModule());

    private JSONUtils() {

    }

    public static ObjectMapper getInstance() {
        return objectMapper;
    }

    /**
     *  实体类转化为json
     */
    public static String objToJson(Object obj) throws JsonProcessingException {
        return objectMapper.writeValueAsString(obj);
    }

    /**
     * 实体类转化为json  输出更优雅
     */
    public static String objToPrettyJson(Object obj) throws JsonProcessingException {
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
    }

    /**
     * json字符串转为实体类对象
     */
    public static <T> T jsonToPojo(String jsonStr, Class<T> clazz)
            throws IOException {
        return objectMapper.readValue(jsonStr, clazz);
    }

    /**
     * json字符串转为map集合对象
     */
    public static Map<String, Object> jsonToMap(String jsonStr)
            throws IOException {
        return objectMapper.readValue(jsonStr, Map.class);
    }


    /**
    *    内嵌json字符串是一个pojo   转化为 map<String,pojo>   "{ \"user\":  {\"name\":\"ludashi\"}  }";
    * */
    public static <T> Map<String, T> jsonToMap(String jsonStr, Class<T> clazz)
            throws IOException {


        Map<String, Object> map = jsonToMap(jsonStr);

        Map<String, T>  map2=new HashMap<String,T>();
        for (String s : map.keySet()) {
            Map o = (Map)map.get(s);
            T t = mapToPojo(o, clazz);
            map2.put(s,t);
        }

        return map2;
    }

    /**
     * map集合  封装为实体类    ObjectMapper可以实现对象到json等其他格式的互转。
     */
    public static <T> T mapToPojo(Map map, Class<T> clazz) {

        return objectMapper.convertValue(map, clazz);
    }
}
